package com.demo.common.utils.compare;

import com.demo.common.cache.CacheService;
import com.demo.common.utils.CacheKeyConstants;
import com.demo.entity.SysRole;
import com.demo.enums.SysUserStatusEnum;
import com.demo.service.SysRoleService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * 字段对比convert注册器
 */
@Component
public class FieldCompareConvertRegister implements InitializingBean {
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private CacheService cacheService;
    @Override
    public void afterPropertiesSet() throws Exception {
        //和excel里面的convert是一样的，类似的，两个都需要转换
        FieldCompareUtils.registerShow(CompareConvertName.SHOW_SYS_ROLE_NAME,(roleId)->{
            String key= CacheKeyConstants.ROLE_ID_NAME+roleId;
            String roleName=cacheService.getCache(key);
            if(roleName==null){
                SysRole one = sysRoleService.getById((Integer)roleId);
                if(one==null){
                    roleName="id为"+roleId+"的角色不存在";
                }else{
                    roleName=one.getRoleName();
                }
                cacheService.setCache(key,roleName,60);
            }
            return roleName;
        });
        //用户状态枚举
        FieldCompareUtils.registerShow(CompareConvertName.SHOW_SYS_STATUS,(status)-> SysUserStatusEnum.of((Integer) status));

        //valueConverter是用来比较值的，比如业务场景认为null和0是一样的，那么就需要进行转换，把null转成0，那么两个0就是一样的，就不会记录对比日志
        //TODO 需要转换值才能比较的场景都可以加这个来处理
        FieldCompareUtils.registerValue(CompareConvertName.VALUE_NULL_TO_ZERO,(data)-> Optional.ofNullable(data).orElse(0));

    }
}
